package com.dream.app.service.impl;

import java.util.Date;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dream.app.cache.AppGroupCache;
import com.dream.app.cache.AppGroupResourceCache;
import com.dream.app.service.GroupService;
import com.dream.dao.base.AppGroupDAO;
import com.dream.dao.base.AppGroupResourceDAO;
import com.dream.model.app.AppAbstractUser;
import com.dream.model.app.AppGroup;
import com.dream.model.app.AppGroupResource;
import com.dream.model.app.AppGroupResource.AppGroupResourcePK;
import com.dream.utils.hibernate.PagingVO;
import com.dream.vo.app.GroupVO;
/**
 * 
 * @copyright evan
 * @author evan
 * @Revision
 * @date 2013-9-8
 */
@Service("GroupService")
public class GroupServiceImpl implements GroupService{

	@Autowired
	private AppGroupDAO appGroupDAO;
	
	@Autowired
	private AppGroupResourceDAO appGroupResourceDAO;
	
	@Autowired
	private AppGroupCache appGroupCache;
	
	@Autowired
	private AppGroupResourceCache appGroupResourceCache;
	
	@Override
	@Transactional
	public boolean existed(final String groupId) {
		
		return appGroupCache.getById(groupId) == null ? false : true;
	}

	@Override
	@Transactional
	public void add(final GroupVO vo, final AppAbstractUser user) {
		
		AppGroup group = new AppGroup();
		group.setId(vo.getId());
		group.setName(vo.getName());
		group.setCreateUser(user.getId());
		group.setCreateTime(new Date());
		
		appGroupDAO.save(group);
		appGroupCache.reload();
		updateGrpRes(vo, user);
	}

	@Override
	@Transactional
	public void modify(final GroupVO vo, final AppAbstractUser user) {
		
		AppGroup group = appGroupDAO.selectById(vo.getId());
		group.setName(vo.getName());
		group.setUpdateUser(user.getId());
		group.setUpdateTime(new Date());
		
		appGroupDAO.saveOrUpdate(group);
		updateGrpRes(vo, user);
	}
	
	@Transactional
	private void updateGrpRes(final GroupVO vo,final AppAbstractUser user) {
		if(ArrayUtils.isNotEmpty(vo.getResources())){
			
			appGroupResourceDAO.delete(vo.getId());
			for(Long resId : vo.getResources()){
				
				AppGroupResource gr = new AppGroupResource();
				gr.setDeleted(false);
				
				AppGroupResourcePK pk = new AppGroupResourcePK();
				pk.setGroupId(vo.getId());
				pk.setResourceId(resId);
				gr.setId(pk);
				
				gr.setCreateUser(user.getId());
				gr.setCreateTime(new Date());
				
				appGroupResourceDAO.save(gr);
			}
			appGroupResourceCache.reload(vo.getId());
		}
	}
	
	@Override
	@Transactional
	public PagingVO query(final GroupVO vo, final PagingVO pageVO) {
		
		return appGroupDAO.query(pageVO);
	}

	@Override
	@Transactional
	public void delete(final String groupId) {
		
		appGroupDAO.delete(groupId);
		appGroupResourceDAO.delete(groupId);
		appGroupCache.reload();
		appGroupResourceCache.reload(groupId);
		
	}

}